package cn.rkylin.oms.goods.service;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.apollo.common.util.SnoGerUtil;
import cn.rkylin.oms.category.vo.MdmCategoryVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.rkylin.core.IDataBaseFactory;
import cn.rkylin.core.service.ApolloService;
import cn.rkylin.oms.category.vo.GoodsCategoryInfoVO;
import cn.rkylin.oms.goods.dao.IGoodsCategoryDAO;
import cn.rkylin.oms.goods.dao.IGoodsDAO;
import cn.rkylin.oms.goods.vo.GoodsCategoryVO;
import cn.rkylin.oms.goods.vo.GoodsVO;

@Service("goodsCategoryService")
public class GoodsCategoryServiceImpl extends ApolloService implements IGoodsCategoryService {

    @Autowired
    private IDataBaseFactory dao;

    @Autowired
    private IGoodsDAO goodsDAO;

    @Value("${mdm.server.url}")
    private String mdmServerUrl;

    @Value("${mdm.server.security}")
    private String mdmServerSecurity;

    @Value("${mdm.server.appId}")
    private String mdmServerAppId;

    private static Map<String,GoodsCategoryVO> GoodsCategory_MAP = new HashMap<String, GoodsCategoryVO>();//只是返回主数据的相关的数据，那种非主数据的没有放在这里

    /**
     * 系统商品数据访问
     */
    @Autowired
    private IGoodsCategoryDAO goodsCategoryDAO;

    @Override
    public List<GoodsCategoryVO> getAllData(String entId) throws Exception {
        List<GoodsCategoryVO> list = dao.findList("selectAllDataGoodsCategory", entId);
        return list;
    }

    private Map<String, String> checkData(GoodsCategoryInfoVO goodsCategoryInfoVO) {
        Map<String, String> result = new HashMap<String, String>();
        result.put("isOk", "y");

        if (goodsCategoryInfoVO == null) {
            result.put("errorMessage", "画面传递参数有问题");
            result.put("isOk", "n");
            return result;
        }

        if ("insert".equals(goodsCategoryInfoVO.getAction())) {
            if (StringUtils.isBlank(goodsCategoryInfoVO.getCatgName())) {
                result.put("errorMessage", "请输入分类名称");
                result.put("isOk", "n");
                return result;
            }
        } else if ("update".equals(goodsCategoryInfoVO.getAction())) {
            if (StringUtils.isBlank(goodsCategoryInfoVO.getKey())) {
                result.put("errorMessage", "要修改的数据不存在");
                result.put("isOk", "n");
                return result;
            }
        } else {
            result.put("errorMessage", "画面传递的处理模式有问题");
            result.put("isOk", "n");
            return result;
        }

        result.put("errorMessage", "");
        result.put("isOk", "y");

        return result;

    }

    @Override
    public Map<String, Object> modifyData(GoodsCategoryInfoVO goodsCategoryInfoVO, Map<String, String> map) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();

        // check
        Map<String, String> checkMap = checkData(goodsCategoryInfoVO);
        if ("n".equals(checkMap.get("isOk"))) {
            result.put("isOk", "n");
            result.put("count", "0");
            result.put("errorMessage", checkMap.get("errorMessage"));
            return result;
        }
        GoodsCategoryVO goodsCategoryVO = new GoodsCategoryVO();
        if ("insert".equals(goodsCategoryInfoVO.getAction())) {
            goodsCategoryVO.setCatgId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
            goodsCategoryVO.setCatgName(goodsCategoryInfoVO.getCatgName());
            goodsCategoryVO.setCreateTime(new Date());
            goodsCategoryVO.setUpdateTime(new Date());
            goodsCategoryVO.setDeleted("n");
            goodsCategoryVO.setEntId(map.get("entId"));
            if (StringUtils.isNotBlank(goodsCategoryInfoVO.getParentKey())) {
                goodsCategoryVO.setParentCatgId(goodsCategoryInfoVO.getParentKey());
            } else {
                goodsCategoryVO.setParentCatgId(null);
            }
            goodsCategoryVO.setRemark(goodsCategoryInfoVO.getRemark());
            goodsCategoryDAO.insert(goodsCategoryVO);

        } else if ("update".equals(goodsCategoryInfoVO.getAction())) {
            goodsCategoryVO.setCatgId(goodsCategoryInfoVO.getKey());
            goodsCategoryVO.setUpdateTime(new Date());
            goodsCategoryVO.setCatgName(goodsCategoryInfoVO.getCatgName());
            goodsCategoryVO.setRemark(goodsCategoryInfoVO.getRemark());
            goodsCategoryDAO.update(goodsCategoryVO);

            //
            GoodsVO goodsVO = new GoodsVO();
            goodsVO.setUpdateTime(new Date());
            goodsVO.setCatgId(goodsCategoryInfoVO.getKey());
            ;
            goodsVO.setCatgName(goodsCategoryInfoVO.getCatgName());
            goodsDAO.updateCatgNameByCatgId(goodsVO);
        }
        String mark = goodsCategoryVO.getCatgId();
        while (StringUtils.isNotBlank(mark)) {
            List<GoodsCategoryVO> listGoodsCategoryVO = dao.findList("selectByPrimaryKeyGoodsCategory", mark);
            if (listGoodsCategoryVO != null && listGoodsCategoryVO.size() > 0) {
                mark = listGoodsCategoryVO.get(0).getParentCatgId();
                GoodsCategoryVO goodsCategory = new GoodsCategoryVO();
                goodsCategory.setCatgId(mark);
                goodsCategory.setUpdateTime(new Date());
                goodsCategoryDAO.update(goodsCategory);
            } else {
                mark = "";
            }
        }

        result.put("isOk", "y");
        result.put("count", "1");
        result.put("errorMessage", "");
        return result;
    }

    private boolean isUsedCategory(String key) throws Exception {
        boolean flg = false;

        List<GoodsVO> list = dao.findList("selectGoodsByCatgId", key);
        if (list != null && list.size() > 0) {
            flg = true;
        } else {
            List<GoodsCategoryVO> listGoodsCategoryVO = dao.findList("selectChildrenByParentCatgId", key);
            if (listGoodsCategoryVO != null && listGoodsCategoryVO.size() > 0) {
                for (int i = 0; i < listGoodsCategoryVO.size(); i++) {
                    if (isUsedCategory(listGoodsCategoryVO.get(i).getCatgId())) {
                        return true;
                    }
                }
            }
        }

        return flg;
    }

    private void deleteCategory(String key) throws Exception {
        GoodsCategoryVO goodsCategoryVO = new GoodsCategoryVO();
        goodsCategoryVO.setCatgId(key);
        goodsCategoryVO.setUpdateTime(new Date());
        goodsCategoryVO.setDeleted("y");
        goodsCategoryDAO.update(goodsCategoryVO);

        List<GoodsCategoryVO> listGoodsCategoryVO = dao.findList("selectChildrenByParentCatgId", key);
        if (listGoodsCategoryVO != null && listGoodsCategoryVO.size() > 0) {
            for (int i = 0; i < listGoodsCategoryVO.size(); i++) {
                deleteCategory(listGoodsCategoryVO.get(i).getCatgId());
            }
        }

    }

    @Override
    public Map<String, Object> deleteData(String key) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        if (StringUtils.isBlank(key)) {
            result.put("isOk", "n");
            result.put("count", "0");
            result.put("errorMessage", "要删除的数据不存在");
            return result;
        }

        //
        if (isUsedCategory(key)) {
            result.put("isOk", "n");
            result.put("count", "0");
            result.put("errorMessage", "系统商品中正在用该商品分类，不能删除");
            return result;
        }

        deleteCategory(key);

        result.put("isOk", "y");
        result.put("count", "1");
        result.put("errorMessage", "");
        return result;
    }

    /**
     *
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> downLoadGoodsCategory(String entId , String mdm_code) throws Exception {
        Map<String, Object> map = downLoadCategory("1",0, entId , mdm_code);
        return  map;
    }

    private Map<String, Object> downLoadCategory(String page,int rows, String entId, String mdm_code) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String data = "{\"system_code\":\"ERP001\",\"page\":"+page+",\"page_size\":\"1000\"}";
        String t = String.valueOf((new Date()).getTime());
        String sign = MD5(mdmServerSecurity + t + data);

        StringBuffer sb = new StringBuffer();
        sb.append(mdmServerUrl+ "/api/mdm_goods_category_instance/query" + "?");
        sb.append("appId=" + mdmServerAppId );
        sb.append("&timestamp=" + t);
        sb.append("&sign=" + sign);
        sb.append("&system_code=ERP001&page="+page+"&page_size=1000");
        if (StringUtils.isNotBlank(mdm_code)){
            sb.append("&mdm_code=" + mdm_code);
        }

        String json = HttpUtils.sendByPost(sb.toString(), data);//HttpUtils.sendByGet(sb.toString(), null);
        System.out.println(json);

        MdmCategoryVO mdmCategoryVO = JSON.parseObject(json, MdmCategoryVO.class);
        List<String> listRecodesJson = JSON.parseArray(mdmCategoryVO.getResult().getData().getRecords(), String.class);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (mdmCategoryVO!=null && "S1".equals(mdmCategoryVO.getStatus())){
            if (mdmCategoryVO.getResult()!=null && "Y1".equals(mdmCategoryVO.getResult().getStatus())){
                if (listRecodesJson!=null && listRecodesJson.size()>0){
                    Map<String ,String> map = new HashMap<String,String>();
                    for (int i = 0 ; i < listRecodesJson.size() ; i++){
                        Map<String, Object> jsonMap = JSONObject.parseObject(listRecodesJson.get(i), new TypeReference<Map<String, Object>>() {
                        });
                        if (jsonMap!=null){
                            GoodsCategoryVO goodsCategoryVO = new GoodsCategoryVO();
                            goodsCategoryVO.setEntId(entId);
                            goodsCategoryVO.setCatgName((String)jsonMap.get("category_name"));
                            if (StringUtils.isNotBlank((String)jsonMap.get("parent_category_code"))){
                                String parentId = "";
                                String jsonParentId =(String)jsonMap.get("parent_category_code");
                                String temp[] = jsonParentId.split("\\.");
                                if (temp!=null && temp.length>0){
                                    for (int j = 0 ; j < temp.length ; j++){
                                        parentId = temp[j];
                                    }
                                }else{
                                    parentId = jsonParentId;
                                }
                                goodsCategoryVO.setParentCatgId(parentId);
                            }

                            if (jsonMap.get("remark")!=null){
                                goodsCategoryVO.setRemark((String)jsonMap.get("remark"));
                            }
                            goodsCategoryVO.setMdmCode((String)jsonMap.get("mdm_code"));
                            goodsCategoryVO.setMdmResponse(listRecodesJson.get(i));
                            String categoryId = "";
                            String jsonCategoryIdId =(String)jsonMap.get("category_code");
                            String temp[] = jsonCategoryIdId.split("\\.");
                            if (temp!=null && temp.length>0){
                                for (int j = 0 ; j < temp.length ; j++){
                                    categoryId = temp[j];
                                }
                            } else {
                                categoryId = jsonCategoryIdId;
                            }
                            goodsCategoryVO.setCatgId(categoryId);
                            GoodsCategoryVO vo = (GoodsCategoryVO) dao.findOne("selectByPrimaryKeyGoodsCategory", categoryId);

                            if (vo!=null) {
                                //更新
                                goodsCategoryDAO.update(goodsCategoryVO);
                                GoodsCategory_MAP.put(categoryId,goodsCategoryVO);
                                //商品的名字的变更
                                GoodsVO goodsVO = new GoodsVO();
                                goodsVO.setUpdateTime(new Date());
                                goodsVO.setCatgId(categoryId);
                                goodsVO.setCatgName((String)jsonMap.get("category_name"));
                                goodsDAO.updateCatgNameByCatgId(goodsVO);

                            } else {
                                //插入
                                goodsCategoryDAO.insert(goodsCategoryVO);
                                GoodsCategory_MAP.put(categoryId,goodsCategoryVO);
                            }
                        }
                    }
                    rows = rows + listRecodesJson.size();
                    if (Integer.valueOf(mdmCategoryVO.getResult().getData().getTotalCount())- rows > 0){
                        Map<String,Object> returnMap = downLoadCategory(String.valueOf(Integer.valueOf(page)+1),rows,entId, mdm_code);
                        rows =  rows + Integer.valueOf((String)returnMap.get("size"));
                        resultMap.put("msg",returnMap.get("msg"));
                    }
                }
            } else if(mdmCategoryVO.getResult()!=null && "Y2".equals(mdmCategoryVO.getResult().getStatus())){
                resultMap.put("size","0");
                resultMap.put("msg","参数错误");
            } else if(mdmCategoryVO.getResult()!=null && "Y3".equals(mdmCategoryVO.getResult().getStatus())){
                resultMap.put("size","0");
                resultMap.put("msg","唯一性校验失败");
            } else if(mdmCategoryVO.getResult()!=null && "Y4".equals(mdmCategoryVO.getResult().getStatus())){
                resultMap.put("size","0");
                resultMap.put("msg","数据状态异常");
            }
        } else if(mdmCategoryVO!=null && "S2".equals(mdmCategoryVO.getStatus())){
            resultMap.put("size","0");
        } else if(mdmCategoryVO!=null && "S3".equals(mdmCategoryVO.getStatus())){
            resultMap.put("size","0");
        } else if(mdmCategoryVO!=null && "S4".equals(mdmCategoryVO.getStatus())){
            resultMap.put("size","0");
        } else {

        }
        if (mdmCategoryVO!=null && resultMap.get("msg")==null){
            resultMap.put("msg",mdmCategoryVO.getMessage());
        }
        resultMap.put("size",String.valueOf(rows));
        if (Integer.valueOf(mdmCategoryVO.getResult().getData().getTotalCount())- rows > 0){
            resultMap.put("success","n");
        } else {
            resultMap.put("success","y");
        }
        return resultMap;
    }

    private String MD5(String message) {
        String mess = message;
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        try {
            byte[] btInput = mess.getBytes("UTF-8");
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Map<String, Object> changeParentKey(String key, String newParentkey) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        if (StringUtils.isBlank(key)) {
            result.put("isOk", "n");
            result.put("count", "0");
            result.put("errorMessage", "要删除的数据不存在");
            return result;
        }

        if (StringUtils.isBlank(newParentkey)) {
            result.put("isOk", "n");
            result.put("count", "0");
            result.put("errorMessage", "要变更的数据变更后的父节点不存在");
            return result;
        }
        GoodsCategoryVO goodsCategoryVO = new GoodsCategoryVO();
        goodsCategoryVO.setCatgId(key);
        goodsCategoryVO.setParentCatgId(newParentkey);
        goodsCategoryVO.setUpdateTime(new Date());
        goodsCategoryDAO.update(goodsCategoryVO);

        result.put("isOk", "y");
        result.put("count", "1");
        result.put("errorMessage", "");
        return result;
    }

    public Object receiveGoodsCategory(String json,String type,String entId) throws Exception {
        List<String> listRecodesJson = JSON.parseArray(json, String.class);
        if (listRecodesJson!=null && listRecodesJson.size()>0){
            for (int i = 0 ; i < listRecodesJson.size() ; i++){
                Map<String, Object> jsonMap = JSONObject.parseObject(listRecodesJson.get(i), new TypeReference<Map<String, Object>>() {
                });
                if (jsonMap!=null){
                    GoodsCategoryVO goodsCategoryVO = new GoodsCategoryVO();
                    goodsCategoryVO.setEntId(entId);
                    goodsCategoryVO.setCatgName((String)jsonMap.get("category_name"));
                    if (StringUtils.isNotBlank((String)jsonMap.get("parent_category_code"))){
                        String parentId = "";
                        String jsonParentId =(String)jsonMap.get("parent_category_code");
                        String temp[] = jsonParentId.split("\\.");
                        if (temp!=null && temp.length>0){
                            for (int j = 0 ; j < temp.length ; j++){
                                parentId = temp[j];
                            }
                        }else{
                            parentId = jsonParentId;
                        }
                        goodsCategoryVO.setParentCatgId(parentId);
                    }

                    if (jsonMap.get("remark")!=null){
                        goodsCategoryVO.setRemark((String)jsonMap.get("remark"));
                    }
                    goodsCategoryVO.setMdmCode((String)jsonMap.get("mdm_code"));
                    goodsCategoryVO.setMdmResponse(listRecodesJson.get(i));
                    String categoryId = "";
                    String jsonCategoryIdId =(String)jsonMap.get("category_code");
                    String temp[] = jsonCategoryIdId.split("\\.");
                    if (temp!=null && temp.length>0){
                        for (int j = 0 ; j < temp.length ; j++){
                            categoryId = temp[j];
                        }
                    } else {
                        categoryId = jsonCategoryIdId;
                    }
                    goodsCategoryVO.setCatgId(categoryId);
                    GoodsCategoryVO vo = (GoodsCategoryVO) dao.findOne("selectByPrimaryKeyGoodsCategory", categoryId);

                    if (vo!=null) {
                        //更新
                        goodsCategoryDAO.update(goodsCategoryVO);
                        GoodsCategory_MAP.put(categoryId,goodsCategoryVO);
                    } else {
                        //插入
                        goodsCategoryDAO.insert(goodsCategoryVO);
                        GoodsCategory_MAP.put(categoryId,goodsCategoryVO);
                    }
                }
            }
        }
        return null;
    }

    public GoodsCategoryVO getGoodsCategoryVO(String entId,String id) throws Exception{

        GoodsCategoryVO vo = GoodsCategory_MAP.get("id");

        if (vo==null){
            downLoadGoodsCategory(entId,"");

            vo = GoodsCategory_MAP.get("id");
            if (vo==null){
                throw new Exception("商品分类ID是"+id+"的分类数据不存在");
            }
        }

        return vo;

    }
}
